<template>
  <div class="date-time-picker">
    <div class="date-range-section">
      <!-- 日期范围选项 -->
      <div
        class="range-option"
        :class="{ 'range-option-active': currentRange === 'lastWeek' }"
        @click="handleRangeSelect('lastWeek')"
      >
        Last Week
      </div>
      <div
        class="range-option"
        :class="{ 'range-option-active': currentRange === 'lastMonth' }"
        @click="handleRangeSelect('lastMonth')"
      >
        Last Month
      </div>
      <div
        class="range-option"
        :class="{ 'range-option-active': currentRange === 'last3Months' }"
        @click="handleRangeSelect('last3Months')"
      >
        Last 3 months
      </div>

      <!-- 自定义日期范围 -->
      <div class="date-picker-group">
        <div class="date-range-label">Date Range</div>
        <div class="custom-date-container">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            align="right"
            unlink-panels
            format="dd/MM/yyyy"
            range-separator="—"
            size="large"
            class="transparent-date-picker"
            :picker-options="pickerOptions"
            @change="handleDateRangeChange"
          />
        </div>
      </div>
    </div>

    <div class="filter-section">
      <div class="frequency-filter">
        <div class="filter-label">frequency</div>

        <div class="frequency-select">
          <el-select
            v-model="selectedFrequency"
            class="filter-select"
            @change="onFrequencyChange"
          >
            <el-option
              v-for="option in filteredFrequencyOpts"
              :key="option.value"
              :label="option.label"
              :value="option.value"
              size="small"
            />
          </el-select>
        </div>
      </div>
      <!-- 刷新按钮 -->
      <div class="refresh-btn">
        <img
          src="@/assets/refresh.png"
          alt="Refresh"
          class="refresh-icon"
          @click="handleRefresh"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      frequencyOptsMap: {
        lastWeek: ["Week", "Day"],
        lastMonth: ["Day", "Week", "Month"],
        last3Months: ["Day", "Week", "Month"],
      },
      allFrequencyOpts: [
        { value: "Day", label: "Day" },
        { value: "Week", label: "Week" },
        { value: "Month", label: "Month" },
      ],

      currentRange: "lastMonth", // 默认选中上个月
      selectedFrequency: "Week", // 默认频率为周
      dateRange: [], // 初始化日期范围为空，在mounted中设置
      isCustomRange: false, // 标记是否为自定义范围

      // 记录当前日期（避免多次计算）
      today: new Date(),
      pickerOptions: {
        disabledDate: this.disabledFutureDate,
      },
    };
  },

  computed: {
    filteredFrequencyOpts() {
      // 如果是自定义范围，显示所有频率选项
      if (this.isCustomRange) {
        return this.allFrequencyOpts;
      }

      const allowedValues = this.frequencyOptsMap[this.currentRange] || [];
      return this.allFrequencyOpts.filter((item) =>
        allowedValues.includes(item.value)
      );
    },

    displayRangeText() {
      if (this.isCustomRange && this.dateRange && this.dateRange.length === 2) {
        const start = this.formatDate(this.dateRange[0]);
        const end = this.formatDate(this.dateRange[1]);
        return `${start} — ${end}`;
      }
      return this.currentRange || "not selected";
    },
  },

  mounted() {
    this.injectCalendarIcon();
    this.setDefaultDateRange(); // 设置默认日期范围
    this.logCurrentSelection();
    this.today.setHours(0, 0, 0, 0); // 初始化今天的日期（仅日期部分）
  },

  methods: {
    // 禁用未来日期
    disabledFutureDate(time) {
      // 获取当前日期（去掉时分秒）
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      // 禁用所有今天之后的日期
      return time > today;
    },
    // 设置默认日期范围
    setDefaultDateRange() {
      this.isCustomRange = false; // 重置为非自定义范围

      if (this.currentRange === "lastMonth") {
        this.dateRange = this.getPreviousMonthRange();
      } else if (this.currentRange === "lastWeek") {
        this.dateRange = this.getPreviousWeekRange();
      } else if (this.currentRange === "last3Months") {
        this.dateRange = this.getPrevious3MonthsRange();
      }
    },

    // 获取上周日期范围
    getPreviousWeekRange() {
      const end = new Date();
      const start = new Date();
      start.setTime(end.getTime() - 7 * 24 * 3600 * 1000);
      return [start, end];
    },

    // 获取上月日期范围（动态计算，例如5.19-6.19）
    getPreviousMonthRange() {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);

      const day = start.getDate();
      const month = start.getMonth();
      const year = start.getFullYear();
      const daysInMonth = new Date(year, month + 1, 0).getDate();
      const adjustedDay = Math.min(day, daysInMonth);

      start.setDate(adjustedDay);
      return [start, end];
    },

    // 获取前三个月日期范围（动态计算，非固定每月1号）
    getPrevious3MonthsRange() {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);

      const day = start.getDate();
      const month = start.getMonth();
      const year = start.getFullYear();
      const daysInMonth = new Date(year, month + 1, 0).getDate();
      const adjustedDay = Math.min(day, daysInMonth);

      start.setDate(adjustedDay);
      return [start, end];
    },

    handleRangeSelect(range) {
      this.currentRange = range;
      this.selectedFrequency = "";
      this.setDefaultDateRange();
      this.logCurrentSelection();
    },

    onFrequencyChange(value) {
      this.selectedFrequency = value;
      this.logFrequencySelection();
    },

    handleDateRangeChange(range) {
      if (range && range.length === 2) {
        // 额外验证日期范围（双重保险）
        if (range[1].getTime() > Date.now()) {
          this.$message({
            message: "The end date cannot exceed the current date",
            type: "warning",
            duration: 2000,
          });
          this.setDefaultDateRange();
          return;
        }

        // 检查选择的日期范围是否属于预设范围
        const isIn预设范围 = this.isDateRangeInPreset(range);

        if (!isIn预设范围) {
          // 不属于预设范围，设置为自定义范围
          this.isCustomRange = true;
          this.currentRange = ""; // 清空当前范围选择
          this.selectedFrequency = ""; // 清空频率选择

          // this.$message({
          //   message: "已选择自定义时间范围",
          //   type: "info",
          //   duration: 2000,
          // });
        } else {
          // 属于预设范围，设置对应的currentRange
          this.isCustomRange = false;

          if (this.isSameRange(range, this.getPreviousWeekRange())) {
            this.currentRange = "lastWeek";
          } else if (this.isSameRange(range, this.getPreviousMonthRange())) {
            this.currentRange = "lastMonth";
          } else if (this.isSameRange(range, this.getPrevious3MonthsRange())) {
            this.currentRange = "last3Months";
          }
        }

        // 无论如何都保留用户选择的日期范围
        this.dateRange = range;
        this.logDateRangeSelection(range);
      }
    },

    // 检查两个日期范围是否相同
    isSameRange(range1, range2) {
      if (!range1 || !range2 || range1.length !== 2 || range2.length !== 2) {
        return false;
      }
      return (
        range1[0].getTime() === range2[0].getTime() &&
        range1[1].getTime() === range2[1].getTime()
      );
    },

    // 检查日期范围是否属于预设范围
    isDateRangeInPreset(range) {
      if (!range || range.length !== 2) return false;

      return (
        this.isSameRange(range, this.getPreviousWeekRange()) ||
        this.isSameRange(range, this.getPreviousMonthRange()) ||
        this.isSameRange(range, this.getPrevious3MonthsRange())
      );
    },

    handleRefresh() {
      console.log("刷新数据请求");
      this.logCurrentSelection();
    },

    injectCalendarIcon() {
      const dateInput = document.querySelector(".el-date-editor");
      if (!dateInput) return;

      const iconEl = document.createElement("i");
      iconEl.classList.add("el-icon-date");
      dateInput.appendChild(iconEl);

      Object.assign(iconEl.style, {
        position: "absolute",
        top: "8px",
        right: "20px",
      });
    },

    logCurrentSelection() {
      console.log("--- social当前时间频率选择 ---");
      console.log(
        `当前日期范围: ${
          this.isCustomRange ? "自定义范围" : this.currentRange || "未选择"
        }`
      );

      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = this.formatDate(this.dateRange[0]);
        const endDate = this.formatDate(this.dateRange[1]);
        console.log(`日期范围: ${startDate} — ${endDate}`);
      } else {
        console.log("日期范围: 未选择");
      }

      console.log(`当前频率选择: ${this.selectedFrequency || "未选择"}`);
    },

    logFrequencySelection() {
      const frequencyLabel =
        this.allFrequencyOpts.find(
          (opt) => opt.value === this.selectedFrequency
        )?.label || this.selectedFrequency;

      console.log(`频率已选择: ${frequencyLabel}`);
      this.logCurrentSelection();
    },

    logDateRangeSelection(range) {
      const startDate = this.formatDate(range[0]);
      const endDate = this.formatDate(range[1]);
      console.log(`日期范围已选择: ${startDate} — ${endDate}`);
      this.logCurrentSelection();
    },

    formatDate(date) {
      if (!date) return "not selected";
      return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
    },
  },
};
</script>

<style lang="scss" scoped>
.date-time-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 75px;
  margin-top: 20px;
  padding: 0 24px;
  border: 1px solid #cdcccc;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}

.date-range-section {
  display: flex;
  align-items: center;
  gap: 16px;

  .date-picker-group {
    width: 249px;
    height: 52px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    border: 1px solid #6a6969;
    border-radius: 8px;
    padding: 4px 0 0;
  }
}

.range-option {
  padding: 10px 16px;
  font-size: 16px;
  font-weight: 400;
  color: #6a6969;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;

  &.range-option-active {
    background-color: #4199e1;
    color: #fff;
    font-size: 16px;
    font-weight: 600;
  }
}

.date-range-label {
  padding: 0 14px;
  font-size: 10px;
  font-weight: 400;
  color: #8f8f8f;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 16px;

  .frequency-filter {
    border: 1px solid #6a6969;
    width: 249px;
    height: 52px;
    border-radius: 8px;
    padding: 4px 15px;
  }
}

.filter-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.frequency-select {
  width: 100%;
  height: 36px;
  padding: 4px 0;
}

.refresh-btn {
  width: 35px;
  height: 35px;
  margin-left: 16px;

  .refresh-icon {
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
}

::v-deep.el-date-editor .el-range-separator {
  line-height: 27px;
}

.custom-date-container {
  ::v-deep .el-input__inner {
    border: 1px solid #fff;
    border-radius: 8px;
    width: 246px;
    height: 35px;
    display: flex;
    align-items: center;
    text-align: center;
    padding: 3px 0;
  }

  ::v-deep.el-input__suffix {
    right: -90px;
    color: #000 !important;
  }

  .frequency-filter {
    ::v-deep .el-select {
      width: 100% !important;
    }
  }

  ::v-deep .el-range__icon {
    display: none;
  }
}

::v-deep .el-input__inner {
  background-color: transparent !important;
  height: 20px;
  padding: 12px 0px;
  color: #000 !important;
  border: none;
}

.date-time-picker .custom-date-container ::v-deep .el-input__inner {
  color: #000 !important;
}

::v-deep.el-date-editor .el-range-input {
  color: #000 !important;
}

::v-deep .el-select .el-input .el-select__caret {
  color: #232323;
}
</style>
